<template>
  <!-- 用户订单列表 -->
  <layout className="identity" title="身份认证">
    <div v-if="loaded">
      <view class="title">请按提示上传身份证照片</view>
      <view class="card" @tap="look">
        <image
          class="photo"
          v-show="photo_1 === ''"
          :src="getImgSrc('/identity/icon_photo@2x.png')"
        />
        <image
          v-if="photo_1 === ''"
          class="identity-cover positive"
          :src="getImgSrc('/identity/img_id_positive@2x.png')"
        />
        <image
          v-else
          class="identity-card positive"
          :src="photo_1"
          mode="widthFix"
        />
        <view v-show="photo_1 === ''" class="card-tip">正面照</view>
      </view>
      <view class="card" @tap="triggerToUpload('photo_2')">
        <image
          v-show="photo_2 === ''"
          class="photo"
          :src="getImgSrc('/identity/icon_photo@2x.png')"
        />
        <image
          v-if="photo_2 === ''"
          class="identity-cover negative"
          :src="getImgSrc('/identity/img_id_negative@2x.png')"
        />
        <image
          v-else
          class="identity-card positive"
          :src="photo_2"
          mode="widthFix"
        />
        <view v-show="photo_2 === ''" class="card-tip">反面照</view>
      </view>
      <view class="title">请上传相关照片（选填）</view>
      <view class="card" @tap="triggerToUpload('photo_3')">
        <image
          v-show="photo_3 === ''"
          class="photo"
          :src="getImgSrc('/identity/icon_photo@2x.png')"
        />
        <image
          v-if="photo_3 === ''"
          class="identity-cover positive"
          :src="getImgSrc('/identity/img_id_positive@2x.png')"
        />
        <image
          v-else
          class="identity-card positive"
          :src="photo_3"
          mode="widthFix"
        />
        <view v-show="photo_3 === ''" class="card-tip">正面照</view>
      </view>

      <u-form
        class="form"
        labelPosition="left"
        :model="model"
        :rules="rules"
        ref="uForm"
      >
        <u-form-item label="姓名" prop="name" borderBottom>
          <u-input
            placeholder="上传身份证自动填充"
            style="text-align: right"
            disabled
            v-model="model.name"
            :border="false"
          />
        </u-form-item>
        <u-form-item label="证件号" prop="id" borderBottom>
          <u-input
            placeholder="上传身份证自动填充"
            style="text-align: right"
            disabled
            v-model="model.id"
            :border="false"
          />
        </u-form-item>
        <u-form-item label="手机号" borderBottom>
          <u-input
            placeholder="点击输入"
            style="text-align: right"
            disabled
            :value="mobile"
            :border="false"
          />
        </u-form-item>
        <u-form-item label="紧急联系人1" prop="tel1" borderBottom>
          <u-input
            placeholder="点击输入"
            style="text-align: right"
            v-model="model.tel1"
            :border="false"
          />
        </u-form-item>
        <u-form-item label="紧急联系人2" prop="tel2" borderBottom>
          <u-input
            placeholder="点击输入"
            style="text-align: right"
            v-model="model.tel2"
            :border="false"
          />
        </u-form-item>
      </u-form>
      <view class="sub-title">当前数据资料只供平台确认信息使用</view>
      <view class="auth-btn" @tap="submit">认证信息</view>
      <u-checkbox-group active-color="#4E95FC" class="schema">
        <u-checkbox v-model="checked" shape="circle"
          >已阅读并同意<text class="schema-link" @tap="togoSS">《点我拿用户服务协议》</text
          ></u-checkbox
        >
      </u-checkbox-group>
    </div>
    <u-loading v-else show></u-loading>
  </layout>
</template>
<script>
import { readImg, compressImg } from "@/common/minizerImg.js";
export default {
  data() {
    return {
      loaded: false,
      model: {
        name: "",
        id: "",
        tel1: "",
        tel2: "",
      },
      photo_1: "",
      photo_2: "",
      photo_3: "",
      checked: false,
      rules: {
        name: {
          required: true,
          message: "请填写姓名",
          trigger: ["blur", "change"],
        },
        id: {
          required: true,
          message: "请输入身份证号",
          trigger: ["blur", "change"],
        },
        tel1: {
          required: true,
          trigger: ["blur", "change"],
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("紧急联系人1必填"));
            } else if (value === this.mobile) {
              callback(new Error("不能与当前账户手机号相同"));
            } else if (!this.$u.test.mobile(value)) {
              callback(new Error("手机号不规范"));
            } else {
              callback();
            }
          },
        },
        tel2: {
          trigger: ["blur", "change"],
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("紧急联系人2必填"));
            } else if (value === this.mobile) {
              callback(new Error("不能与当前账户手机号相同"));
            } else if (value === this.model.tel1) {
              callback(new Error("不能与联系人1相同"));
            } else if (!this.$u.test.mobile(value)) {
              callback(new Error("手机号不规范"));
            } else {
              callback();
            }
          },
        },
      },
    };
  },
  onLoad(option) {
    this.queryCurrentProcess();
  },
  onReady() {
    if (this.$refs.uForm) {
      this.$refs.uForm.setRules(this.rules);
    }
  },
  computed: {
    mobile() {
      return this.vuex_user.mobile || "";
    },
  },
  methods: {
    togoSS() {
      uni.navigateTo({
        url: '/pages/sys/auth/service-schema'
      })
    },
    async compress(file) {
      const img = await readImg(file);
      const blob = await compressImg(img, file.type, 1000, 1000);
      return blob;
    },
    async queryCurrentProcess() {
      this.loaded = false;
      const data = await this.$u.api.queryRealNameProcess();
      const type = data.data.type;
      switch (type) {
        case 1:
          this.loaded = true;
          break;
        case 2:
        case 3:
        case 4:
          uni.redirectTo({
            url: "/pages/sys/auth/realName",
          });
          break;
        case 5:
          uni.redirectTo({
            url: "/pages/sys/auth/result",
          });
          break;
        default:
          uni.showToast({
            title: "未知状态",
            icon: "none",
          });
          break;
      }
    },
    async look() {
      const { imageFiles } = await this.chooseImage();
      const file = await this.compress(imageFiles[0]);
      uni.uploadFile({
        url: this.vuex_config.baseUrl + "/applet/oss/upload",
        file,
        header: {
          Authorization: this.vuex_tokenHead + this.vuex_token,
        },
        name: "file",
        formData: {
          type: "IMG_USER_CARD",
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          this.photo_1 = data.data;
        },
        fail: (err) => {
          console.log("上传失败");
        },
        complete: console.log,
      });

      uni.uploadFile({
        url:
          this.vuex_config.baseUrl + "/applet/runner/validate/card/recognize",
        file: file,
        header: {
          Authorization: this.vuex_tokenHead + this.vuex_token,
        },
        name: "file",
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.code === 200 && data.data) {
            this.requestId = data.data.requestId;
            this.model.id = data.data.num;
            this.model.name = data.data.name;
          } else {
            uni.showToast({
              title: data.message,
              duration: 2000,
              icon: "error",
            });
          }
        },
        fail: (err) => {
          console.log("上传失败");
        },
        complete: console.log,
      });
    },
    chooseImage: () => {
      return new Promise((res, rej) => {
        uni.chooseImage({
          count: 1,
          sizeType: "original",
          success: (e) => {
            res({
              imageList: e.tempFilePaths,
              imageFiles: e.tempFiles,
            });
          },
          fail: () => {
            uni.showToast({
              title: "选择图片失败，请确认权限",
            });
          },
        });
      });
    },
    async triggerToUpload(field) {
      const { imageFiles } = await this.chooseImage();
      const file = await this.compress(imageFiles[0]);
      uni.uploadFile({
        url: this.vuex_config.baseUrl + "/applet/oss/upload",
        file,
        header: {
          Authorization: this.vuex_tokenHead + this.vuex_token,
        },
        name: "file",
        formData: {
          type: "IMG_USER_CARD",
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.code !== 200) {
            uni.showToast({
              title: data.message,
              icon: "none",
            });
            return;
          }
          this[field] = data.data;
        },
        fail: (err) => {
          console.log("上传失败");
        },
        complete: console.log,
      });
    },
    async triggerToSubmit() {
      const data = await this.$u.api.submitRealName({
        idCardBack: this.photo_2,
        requestId: this.requestId,
        stuCard: this.photo_3,
        ...this.model,
      });
      if (data.code !== 200) {
        uni.showToast({
          title: "提交失败" || data.message,
          icon: "none",
        });
        return;
      }
      uni.redirectTo({
        url: "/pages/sys/auth/realName",
      });
    },
    async submit() {
      if (!this.checked) {
        uni.showToast({
          title: "请勾选用户服务协议",
          icon: "none",
        });
        return;
      }

      if (!this.photo_1) {
        uni.showToast({
          title: "请上传身份证",
          icon: "none",
        });
        return;
      }
      

      if (!this.requestId) {
        uni.showToast({
          title: "请上传身份证",
          icon: "none",
        });
        return;
      }

      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.triggerToSubmit();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
